const cloud = require('wx-server-sdk');
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
});
const db = cloud.database();
const setUserInfo=async event=>{
  const wxContext = cloud.getWXContext();
  try{
  const registerResult=await db.collection("User_Profile").where({
    OpenID:wxContext.OPENID
  }).get();
  if(registerResult.data.length===0){
    await db.collection("User_Profile").add({
      data:{
        OpenID:wxContext.OPENID,
        Nickname:event.nickname,
        Avatar:event.avatar,
        Name: event.name,
        Gender:event.gender,
        StudentID: event.studentID,
        StudentType: event.studentType,
        EnrollmentYear:new Date(event.enrollmentYear),
        College: event.college,
        Major: event.major,
        PhoneNumber: event.phoneNumber,
        RegistrationTime: new Date()
      }
    });
    return {
      success:true,
      error:"",
      openID:wxContext.OPENID
    };
  }
  const stats=await db.collection("User_Profile").where({
    OpenID:wxContext.OPENID
  }).update({
    data:{
    Nickname:event.nickname,
    Avatar:event.avatar,
    Name: event.name,
    Gender:event.gender,
    StudentID: event.studentID,
    StudentType: event.studentType,
    EnrollmentYear:new Date(event.enrollmentYear),
    College: event.college,
    Major: event.major,
    PhoneNumber: event.phoneNumber,
    },
  });
  return {
    success:true,
    error:"",
    openID:wxContext.OPENID
  };

  }catch(e){
    return {
      success: false,
      error: e.message || "数据库操作失败",
      openID: wxContext.OPENID
    };
  }
}
exports.main = async (event, context) => {
  return await setUserInfo(event);
};